<template>
  <div class="content">
    <el-button @click="openFormDialog(form,'add')">添加角色</el-button>
    <div style="display: flex;flex-direction: column;align-items: flex-end;">

      <el-table
          :data="datas"
          row-key="id"
          stripe
          :row-style="{height:'40px'}"
          :cell-style="{padding:'0px'}">
        <el-table-column
            prop="name"
            label="角色名称">
        </el-table-column>
        <el-table-column
            prop="code"
            label="角色名称">
        </el-table-column>
        <el-table-column
            prop="introduce"
            label="角色介绍">
        </el-table-column>
        <el-table-column
            label="操作"
            width="200">
          <template slot-scope="scope">
            <el-button @click="openFormDialog(scope.row,'edit')" type="text" size="small">编辑</el-button>
            <el-button @click="deleteById(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination style="margin-top: 5px"
                     @size-change="currentSizeChange"
                     @current-change="currentChange"
                     :current-page="currentPage"
                     :page-sizes="[10, 20, 30, 40]"
                     :page-size="limit"
                     layout="total, sizes, prev, pager, next, jumper"
                     :total="total">
      </el-pagination>

      <el-dialog title="修改角色" :visible.sync="dialogFormVisible" width="600px">
        <el-form :model="form" ref="form">
          <el-form-item label="角色名" prop="name" :label-width="formLabelWidth"
                        :rules="[
                                  { required: true, message: '请填写完整'}
                                ]">
            <el-input v-model="form.name" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="角色码" prop="code" :label-width="formLabelWidth"
                        :rules="[
                                  { required: true, message: '请填写完整'}
                                ]">
            <el-input v-model="form.code" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="角色介绍" prop="introduce" :label-width="formLabelWidth"
                        :rules="[
                                  { required: true, message: '请填写完整'}
                                ]">
            <el-input v-model="form.introduce" autocomplete="off"/>
          </el-form-item>

          <el-form-item label="功能权限" :label-width="formLabelWidth">
            <el-select v-model="defaultPermissionList" multiple placeholder="请选择">
              <el-option
                  v-for="item in permissionList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="菜单权限" :label-width="formLabelWidth">
            <el-cascader
                v-model="defaultMenuList"
                :options="menuTree"
                :props="props"
                collapse-tags
                clearable/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>
export default {
  name: "RoleList",
  data() {
    return {
      page: 1,
      limit: 10,
      total: 0,
      currentPage:1,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      datas: [],
      form: {
        id: '',
        name: '',
        code: '',
        menus:[],
        permissions:[]
      },
      props: {
        multiple: true,
        value:'id',
        label:'name',
        children:'children'
      },
      //已经有
      defaultMenuList:[],
      //所有
      menuTree: [],
      //已经有
      defaultPermissionList:[],
      //所有
      permissionList:[]
    }
  },
  created() {
    this.getDatas()
  },
  methods:{
    getDatas(){
      let url = 'role/'+this.page+"/"+this.limit
      this.$http.get(url).then(res=>{
        if(res.data.code===0){
          this.total = res.data.data.data.total
          this.datas = res.data.data.data.records
          this.getMenu()
          this.getPermission()
        }
      })
    },
    //获取菜单
    getMenu(){
      let url = "menu/tree";
      this.$http.get(url).then(res=>{
        this.menuTree = res.data.data.items
      })
    },
    getPermission(){
      let url = "permission";
      this.$http.get(url).then(res=>{
        this.permissionList = res.data.data.data
      })
    },
    //页面发生改变
    currentChange(value){
      this.page = value
      this.getDatas()
    },
    currentSizeChange(value){
      this.limit = value
      this.getDatas()
    },
    //打开表单
    openFormDialog(row,type){
      this.dialogFormVisible = true
      if(type==='add'){
        this.form = {}
        this.defaultMenuList = []
        this.defaultPermissionList = []
      }
      if(type==='edit'){
        this.form = {...row}
        //菜单
        let menusUrl = 'menu/tree'
        let byRoleIdMenuUrl = 'role/menu/'+this.form.id
        this.$http.get(menusUrl).then((res)=>{
          if(res.data.code === 0){
            this.menuTree = res.data.data.items
            this.$http.get(byRoleIdMenuUrl).then((res)=>{
              if(res.data.code === 0){
                this.defaultMenuList = res.data.data.data
              }
            })
          }
        });
        //权限
        let byRoleIdPermissionUrl = 'role/permission/'+this.form.id
        this.$http.get(byRoleIdPermissionUrl).then(res=>{
          if(res.data.code===0){
            this.defaultPermissionList = res.data.data.data
          }
        })
      }
    },
    // 递归判断列表，把最后的children设为undefined
    getTreeData(data){
      for(let i=0;i<data.length;i++){
        if(data[i].childs){
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].childs);
        }else {
          // children若为空数组，则将children设为undefined
          data[i].childs=undefined;
        }
      }
      return data;
    },
    //提交表单
    submitForm(formName){
      if(this.form.id){
        //取二维数组的每个一维数组的最后一个id存入数据库
        let menus = [];
        if (this.defaultMenuList) {
          for (let item of this.defaultMenuList) {
            let id = item[item.length-1]
            let obj = {}
            obj.id = id
            menus.push(obj)
          }
        }
        this.form.menus = menus
        let permissions = []
        if(this.defaultPermissionList){
          for(let item of this.defaultPermissionList){
            let obj = {}
            obj.id = item
            permissions.push(obj)
          }
        }
        this.form.permissions = permissions
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url = "role"
            this.$http.put(url,this.form).then(res=>{
              if(res.data.code===0){
                this.getDatas()
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '修改成功!'
                });
                this.getDatas()
              }else{
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            })
          } else {
            return false;
          }
        });
      }else{
        //取二维数组的每个一维数组的最后一个id存入数据库
        let menus = [];
        if (this.defaultMenuList) {
          for (let item of this.defaultMenuList) {
            let id = item[item.length-1]
            let obj = {}
            obj.id = id
            menus.push(obj)
          }
        }
        this.form.menus = menus
        let permissions = []
        if(this.defaultPermissionList){
          for(let item of this.defaultPermissionList){
            let obj = {}
            obj.id = item
            permissions.push(obj)
          }
        }
        this.form.permissions = permissions
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let url = "role"
            this.$http.post(url,this.form).then(res=>{
              if(res.data.code===0){
                this.getDatas()
                this.dialogFormVisible = false
                this.$message({
                  type: 'success',
                  message: '添加成功!'
                });
              }else{
                this.$message({
                  type: 'error',
                  message: res.data.msg
                });
              }
            })
          } else {
            return false;
          }
        });
      }
    },
    //根据ID删除
    deleteById(row){
      this.$confirm('确定要删除这条数据吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let url = 'role/'+row.id
        this.$http.delete(url).then(res=>{
          if(res.data.code===0){
            this.getDatas()
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          }else{
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //清空表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
}
</script>

<style scoped>

</style>
